package com.wang.service.impl;

import com.wang.config.MinIOInfo;
import com.wang.service.FileService;
import com.wang.util.CommonUtil;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private MinIOInfo minIOInfo;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private CommonUtil commonUtil;

    //视频上用的是阿里云OSS，这里我替换为minio了
    @Override
    public String uploadUserImage(MultipartFile file) {
        //获取存储桶名
        String bucketName = minIOInfo.getBucketName();

        //拼接文件名    例如：2020/08/08/saladsjfladsf.jpg     user + 日期+由UUID生成的随机数+文件扩展名   user是bucket中文件夹的名称
        //1.使用jdk8新特性获取日期
        LocalDateTime from = LocalDateTime.now();   //获取当前日期
        String format = from.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));//格式化日期
        //2.获取UUID生成的随机数
        String uuid = commonUtil.generateUUID();
        //3.获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //4.拼接文件名
        String object = "user/" + format + "/" + uuid + ext;

        try {
            ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(object)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build());

            if(null != objectWriteResponse){
                return minIOInfo.getEndpoint() + "/" + bucketName + "/" + object;
            }
        } catch (Exception e) {
            log.error("上传文件失败！", e);
        }
        return null;
    }
}
